<template>
  <div class="rule-config">
    <div class="header">
      <div class="header-top">
        <button class="back-button" @click="goToChat">
          <span class="back-icon">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
          </span>
          <span class="back-text">继续对话</span>
        </button>
        <h2>规则配置</h2>
      </div>
      <div class="action-section">
        <div class="search-bar">
          <div class="search-input">
            <i class="search-icon">🔍</i>
            <input 
              v-model="searchName" 
              placeholder="搜索规则名称"
              @input="handleSearch"
            >
          </div>
          <div class="search-input">
            <i class="search-icon">🔍</i>
            <input 
              v-model="searchRule" 
              placeholder="搜索规则"
              @input="handleSearch"
            >
          </div>
          <button class="primary-button" @click="showAddDialog">
            <span class="button-icon">+</span>
            添加规则
          </button>
        </div>
      </div>
    </div>

    <div class="content-section">
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th class="column-id">序号</th>
              <th class="column-name">规则名称</th>
              <th class="column-rule">规则</th>
              <th class="column-actions">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in ruleList" :key="item.id">
              <td class="column-id">{{ (currentPage - 1) * pageSize + index + 1 }}</td>
              <td class="column-name">
                <template v-if="editingItem === item">
                  <input 
                    v-model="editForm.ruleName"
                    class="edit-input"
                    placeholder="请输入规则名称"
                  />
                </template>
                <template v-else>
                  {{ item.rule_name }}
                </template>
              </td>
              <td class="column-rule">
                <template v-if="editingItem === item">
                  <input 
                    v-model="editForm.rule"
                    class="edit-input"
                    placeholder="请输入规则"
                  />
                </template>
                <template v-else>
                  {{ item.rule }}
                </template>
              </td>
              <td class="column-actions">
                <template v-if="editingItem === item">
                  <button class="action-button save" @click="saveEdit(item)">保存</button>
                  <button class="action-button cancel" @click="cancelEdit">取消</button>
                </template>
                <template v-else>
                  <button class="action-button edit" @click="startEdit(item)">编辑</button>
                  <button class="action-button delete" @click="deleteRule(item)">删除</button>
                </template>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="pagination">
        <button 
          class="page-button"
          :disabled="currentPage === 1" 
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        <button 
          class="page-button"
          :disabled="currentPage === totalPages" 
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 添加规则对话框 -->
    <div class="dialog-overlay" v-if="showDialog" @click.self="showDialog = false">
      <div class="dialog">
        <div class="dialog-header">
          <h3>添加规则</h3>
          <button class="close-button" @click="showDialog = false">&times;</button>
        </div>
        <div class="dialog-content">
          <div class="form-item">
            <label>规则名称</label>
            <input 
              v-model="addForm.ruleName"
              class="dialog-input"
              placeholder="请输入规则名称"
            >
          </div>
          <div class="form-item">
            <label>规则</label>
            <input 
              v-model="addForm.rule"
              class="dialog-input"
              placeholder="请输入规则"
            >
          </div>
        </div>
        <div class="dialog-footer">
          <button 
            class="dialog-button cancel" 
            @click="showDialog = false"
          >
            取消
          </button>
          <button 
            class="dialog-button confirm" 
            @click="addRule"
            :disabled="!addForm.ruleName || !addForm.rule"
          >
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '../config'

export default {
  name: 'RuleConfig',
  data() {
    return {
      baseUrl: API_BASE_URL,
      ruleList: [],
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      searchName: '',
      searchRule: '',
      showDialog: false,
      editingItem: null,
      addForm: {
        ruleName: '',
        rule: ''
      },
      editForm: {
        ruleName: '',
        rule: ''
      }
    }
  },

  mounted() {
    this.loadRules()
  },

  methods: {
    async loadRules() {
      try {
        const queryParams = new URLSearchParams({
          page: this.currentPage,
          pageSize: this.pageSize,
          ruleName: this.searchName,
          rule: this.searchRule
        })

        const response = await fetch(`${this.baseUrl}/api/rules?${queryParams}`)
        const data = await response.json()
        this.ruleList = data.items
        this.totalPages = Math.ceil(data.total / this.pageSize)
      } catch (error) {
        console.error('加载规则失败:', error)
      }
    },

    async addRule() {
      try {
        const response = await fetch(`${this.baseUrl}/api/rules`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ruleName: this.addForm.ruleName,
            rule: this.addForm.rule
          })
        })
        
        if (response.ok) {
          this.showDialog = false
          this.addForm.ruleName = ''
          this.addForm.rule = ''
          await this.loadRules()
        }
      } catch (error) {
        console.error('添加规则失败:', error)
      }
    },

    async updateRule(item) {
      try {
        const response = await fetch(`${this.baseUrl}/api/rules/${item.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ruleName: this.editForm.ruleName,
            rule: this.editForm.rule
          })
        })
        
        if (response.ok) {
          this.editingItem = null
          await this.loadRules()
        }
      } catch (error) {
        console.error('更新规则失败:', error)
      }
    },

    async deleteRule(item) {
      if (!confirm('确定要删除这个规则吗？')) return

      try {
        const response = await fetch(`${this.baseUrl}/api/rules/${item.id}`, {
          method: 'DELETE'
        })
        
        if (response.ok) {
          await this.loadRules()
        }
      } catch (error) {
        console.error('删除规则失败:', error)
      }
    },

    showAddDialog() {
      this.showDialog = true
    },

    startEdit(item) {
      this.editingItem = item
      this.editForm.ruleName = item.rule_name
      this.editForm.rule = item.rule
    },

    async saveEdit(item) {
      await this.updateRule(item)
    },

    cancelEdit() {
      this.editingItem = null
    },

    changePage(page) {
      this.currentPage = page
      this.loadRules()
    },

    handleSearch: debounce(function() {
      this.currentPage = 1
      this.loadRules()
    }, 300),

    goToChat() {
      this.$router.push('/')
    }
  }
}

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func.apply(this, args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}
</script>

<style scoped>
.rule-config {
  padding: 32px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 32px;
}

.header-top {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 24px;
}

.back-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #ffffff;
  color: #1976d2;
  border: 1px solid #e3f2fd;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(25, 118, 210, 0.05);
  height: 36px;
}

.back-button:hover {
  background-color: #1976d2;
  color: #ffffff;
  border-color: #1976d2;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(25, 118, 210, 0.15);
}

.header-top h2 {
  font-size: 24px;
  color: #1565c0;
  margin: 0;
}

.action-section {
  margin-top: 24px;
  padding: 16px;
  background: transparent;
  border-radius: 12px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 100px;
}

.search-input {
  position: relative;
  width: 240px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
}

.search-input input {
  width: 100%;
  padding: 10px 12px 10px 36px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background-color: #ffffff;
}

.search-input input:focus {
  border-color: #1976d2;
  outline: none;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.1);
}

.primary-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  white-space: nowrap;
}

.button-icon {
  font-size: 16px;
  font-weight: bold;
}

.content-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 40, 130, 0.08);
  overflow: hidden;
  margin-top: 24px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
  padding: 0 16px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px 12px;
  text-align: center;
  border-bottom: 1px solid #e2e8f0;
  font-size: 14px;
  line-height: 1.4;
}

th {
  background: #f8fafc;
  font-weight: 500;
  color: #1e293b;
  white-space: nowrap;
  padding: 10px 12px;
}

.column-id {
  width: 60px;
}

.column-name, .column-rule {
  min-width: 180px;
  max-width: 300px;
}

.column-actions {
  width: 160px;
  white-space: nowrap;
}

.edit-input {
  width: calc(100% - 24px);
  padding: 4px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
  margin: 0 auto;
  height: 28px;
}

.edit-input:focus {
  border-color: #1976d2;
  outline: none;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.1);
}

.action-button {
  padding: 3px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
  margin-left: 8px;
  height: 24px;
  line-height: 18px;
}

.action-button.edit {
  background: #e3f2fd;
  color: #1976d2;
}

.action-button.delete {
  background: #fee2e2;
  color: #dc2626;
}

.action-button.save {
  background: #1976d2;
  color: white;
}

.action-button.cancel {
  background: #e2e8f0;
  color: #64748b;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;
}

.page-button {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  color: #1e293b;
  cursor: pointer;
  transition: all 0.2s;
}

.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #64748b;
  font-size: 14px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 12px;
  width: 480px;
  max-width: 90vw;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e2e8f0;
}

.dialog-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  color: #64748b;
  cursor: pointer;
  padding: 4px;
}

.dialog-content {
  padding: 24px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #1e293b;
  font-size: 14px;
}

.dialog-input {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
}

.dialog-input:focus {
  border-color: #1976d2;
  outline: none;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e2e8f0;
}

.dialog-button {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.dialog-button.cancel {
  background: #e2e8f0;
  color: #64748b;
}

.dialog-button.confirm {
  background: #1976d2;
  color: white;
}

.dialog-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style> 